#!/usr/bin/env python
# encoding: utf-8
"""
Copyright 2011, 2012 Google Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import os
import libxml2, libxslt

class ValidationError:
	def __init__(self):
		self.errors = []
	def handler(self, msg, data):
		self.errors.append(msg)
	def __str__(self):
		return "%s" % ", ".join(self.errors)

class PackageError(Exception):
	pass

class Library:
	def __init__(self,path,name):
		self._path = path
		self._name = name
		assert path and os.path.isdir(path)
		assert os.path.isdir(self.librarypath)
		self._manifestgen_xslt = self._load_stylesheet("manifest-generate.xslt")
		self._packagegen_xslt = self._load_stylesheet("package-translate.xslt")
		self._package_schema = self._load_schema("schema.xsd")
	# PRIVATE METHODS
	def _load_stylesheet(self,filename):
		stylesheetpath = os.path.join(self.librarypath,filename)
		assert os.path.exists(stylesheetpath)
		manifest_stylesheet_doc = libxml2.parseFile(stylesheetpath)
		return libxslt.parseStylesheetDoc(manifest_stylesheet_doc)
	def _load_schema(self,filename):
		schema_path = os.path.join(self.librarypath,filename)
		schema_context = libxml2.schemaNewParserCtxt(schema_path)
		schema_doc = schema_context.schemaParse()
		return schema_doc
	# PROPERTIES
	def get_librarypath(self):
		return os.path.join(self._path,self._name)
	def get_name(self):
		return self._name
	librarypath = property(get_librarypath)
	name = property(get_name)
	# METHODS
	def package_doc(self,source_doc):
		return self._packagegen_xslt.applyStylesheet(source_doc,None)
	def validate(self,source_doc):
		error = ValidationError()
		schema_handler = self._package_schema.schemaNewValidCtxt()
		schema_handler.setValidityErrorHandler(error.handler,error.handler,None)
		returnValue = source_doc.schemaValidateDoc(schema_handler)
		if returnValue != 0:
			return error

class Package:
	def __init__(self,package_path,library):
		assert package_path and os.path.isfile(package_path)
		assert isinstance(library,Library)
		self._library = library
		self._package_path = os.path.dirname(package_path)
		self._package_source_doc = self._load_document(package_path)
		self._package_destination_doc = library.package_doc(self._package_source_doc)
	# PRIVATE METHODS
	def _load_document(self,filename):
		assert os.path.exists(filename)
		return libxml2.parseFile(filename)
	def _xpath_eval(self,xpath):
		content = list()
		package_context = self.document.xpathNewContext()
		for result in package_context.xpathEval(xpath):
			content.append(result.content)
		return content
	# PROPERTIES
	def get_path(self):
		return os.path.abspath(self._package_path)
	def get_source(self):
		return self._package_source_doc
	def get_document(self):
		return self._package_destination_doc
	def get_name(self):
		value = self._xpath_eval("/package/@name")
		assert value
		return "".join(value)
	path = property(get_path)
	source = property(get_source)
	document = property(get_document)
	name = property(get_name)
	# METHODS
	def validate(self):
		error = self._library.validate(self._package_source_doc)
		if error:
			raise PackageError(str(error))
